import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:getwidget/components/alert/gf_alert.dart';
import 'package:getwidget/components/button/gf_button.dart' show GFButton;
import 'package:getwidget/types/gf_alert_type.dart';
import 'package:http/http.dart' as http;
import 'package:jtlf/common/consts.dart';
import 'package:jtlf/common/pref_utils.dart';
import 'package:jtlf/me/forget_password.dart';
import 'package:jtlf/me/register.dart';
import 'package:jtlf/proto/user/user.pb.dart';
import 'package:fixnum/fixnum.dart';
import 'package:lottie/lottie.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 登录模块
class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _phoneController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _obscurePassword = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFF0088FF), Color(0xFF0066CC)],
          ),
        ),
        child: Center(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(24),
              child: _buildLoginCard(),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildLoginCard() {
    return Card(
      elevation: 8,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox(height: 24),
              _buildLogo(),
              const SizedBox(height: 32),
              _buildPhoneInput(),
              const SizedBox(height: 16),
              _buildPasswordInput(),
              const SizedBox(height: 24),
              _buildLoginButton(),
              const SizedBox(height: 24),
              _buildBottomLinks(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLogo() {
    return Column(
      children: [
        Image.asset(
          'assets/logo.png', // 替换为实际logo路径
          width: 80,
          height: 80,
        ),
        const SizedBox(height: 16),
        const Text(
          '企业协作平台',
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
            color: Color(0xFF0088FF),
          ),
        ),
      ],
    );
  }

  Widget _buildPhoneInput() {
    return TextFormField(
      controller: _phoneController,
      // keyboardType: TextInputType.phone,
      // inputFormatters: [FilteringTextInputFormatter.digitsOnly],
      decoration: const InputDecoration(
        hintText: '手机号',
        prefixIcon: Icon(Icons.phone_iphone),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) return '请输入手机号';
        // if (value.length != 11) return '手机号格式不正确';
        return null;
      },
    );
  }

  Widget _buildPasswordInput() {
    return TextFormField(
      controller: _passwordController,
      obscureText: _obscurePassword,
      decoration: InputDecoration(
        hintText: '密码',
        prefixIcon: const Icon(Icons.lock),
        suffixIcon: IconButton(
          icon: Icon(_obscurePassword ? Icons.visibility : Icons.visibility_off),
          onPressed: () => setState(() => _obscurePassword = !_obscurePassword),
        ),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) return '请输入密码';
        return null;
      },
    );
  }

  Widget _buildLoginButton() {
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton(
        onPressed: _handleLogin,
        child: const Text('登录', style: TextStyle(fontSize: 16)),
      ),
    );
  }

  Widget _buildBottomLinks() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        TextButton(
          onPressed: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (context) => ForgetPasswordScreen()));
          },
          child: const Text('忘记密码'),
        ),
        TextButton(
          onPressed: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (context) => const RegisterScreen()));
          },
          child: const Text('注册账号'),
        ),
      ],
    );
  }

  // 在登录逻辑中添加
  void _handleLogin() async {
    if (_formKey.currentState!.validate()) {
      const tenantId = 'labulaka';
      User user = User.create();
      user.account = _phoneController.text;
      user.password = '123456789a!';
      user.tenantId = tenantId;

      final response = await http.post(
        Uri.parse('$serverUrl/user/login'),
        headers: {
          'content-type': 'application/x-protobuf; charset=UTF-8'
        },
        body: user.writeToBuffer(),
      );

      if (response.statusCode == 200) {
        UserReply reply = UserReply.fromBuffer(response.bodyBytes);
        int code = reply.code;
        String msg = reply.message;
        User user = reply.user;
        if (code == 1) {
          // String tokenId = user.tokenId;
          // Int64 expired = user.replyTime;
          final prefs = await SharedPreferences.getInstance();
          // 将属性保存到prefs中
          login(prefs, user);
          Navigator.pushReplacementNamed(context, '/main');
        } else {
          SmartDialog.showToast(msg, displayTime: const Duration(seconds: 2));

          // 成功提示弹窗
          // AwesomeDialog(
          //   context: context,
          //   dialogType: DialogType.success,
          //   animType: AnimType.bottomSlide,
          //   title: '支付成功',
          //   desc: '订单已处理完毕',
          //   btnOkOnPress: () {},
          //   btnOkColor: Colors.green,
          // ).show();

          // 自定义动画弹窗
          // AwesomeDialog(
          //   context: context,
          //   dialogType: DialogType.noHeader,
          //   body: Padding(
          //     padding: EdgeInsets.all(20),
          //     child: Column(
          //       children: [
          //         Lottie.asset('assets/loading.json', width: 100),
          //         const Text('数据加载中...')
          //       ],
          //     ),
          //   ),
          //   animType: AnimType.bottomSlide,
          //   alignment: Alignment.center,
          // ).show();

        }
      }
    }
  }

}